package com.globagames.strategicgames.view.battles.actions
{
	import com.globagames.isometric.core.event.IsoMapMouseEvent;
	import com.globagames.isometric.core.model.IsoTile;
	import com.globagames.isometric.core.model.SimpleObject;
	import com.globagames.isometric.core.util.CollisionManager;
	import com.globagames.isometric.core.view.actions.IAction;
	import com.globagames.strategicgames.model.Soldier;
	import com.globagames.strategicgames.model.StrategicGameModelLocator;
	import com.globagames.strategicgames.util.SoldierDesigner;
	
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.controls.Label;
	import mx.core.UIComponent;
	
	import org.cove.ape.APEngine;
	import org.cove.ape.CircleParticle;
	import org.cove.ape.Composite;
	import org.cove.ape.RectangleParticle;
	import org.cove.ape.SpringConstraint;
	[Event(name="allDistanceUsed")]	
	[Event(name="selected")]
	public class MoveAction extends UIComponent implements IAction {
		private var model:StrategicGameModelLocator = StrategicGameModelLocator.getInstance();
			
		var soldierDesigner:SoldierDesigner = new SoldierDesigner();	
		private var _soldier:Soldier;
		public var simpleObject:SimpleObject;
		private var movingSoldier:Soldier;
		private var wc:SpringConstraint;
		private var composite:Composite;
		
		private var oldX:int;
		private var oldY:int;
		private var rectangleParticle : RectangleParticle;
		private var circleParticle : CircleParticle;		
		private var soldierIsoSource:SimpleObject;
		public var distanceMax:int =0;
		private var distance:Number =0;
		private var text:Label;
		public var ar:Array;
		var lastMouseX:int = -1;
		var lastMouseY:int = -1;
		var decalageY:int;
		var decalageX:int;
		public var isoTileCharacterCenter:IsoTile;
		
		public function MoveAction() {			
		}
		override protected function createChildren():void{
			super.createChildren();
			this.x = 0;
			this.y = 0;	
			this.width = model.coreModel.screenWidth;
			this.height = model.coreModel.screenHeight;
			text = new Label();
			text.setStyle("color","white");
			text.visible = false;
			this.addChild(text);
			invalidateProperties();					
		}
		public function mouseDownHandler(event:MouseEvent):void {
			trace("MoveAction::mouseDownHandler()");
			model.coreModel.autoScrollingIsOn = true;
			var mX:int = model.coreModel.isoMap.mouseX;
			var mY:int = model.coreModel.isoMap.mouseY;
			var position:IsoMapMouseEvent = model.coreModel.isoMap.getCurrentMousePosition(mX,mY);
			var arSo:Array = model.coreModel.isoMap.getCurrentCharacter(mX,mY,position);
			
			
			if( arSo  ){
				simpleObject = arSo[0] as SimpleObject;
				decalageX = Number(arSo[1]);
				decalageY = Number(arSo[2]);
				mX+= decalageX;
				mY+= decalageY;
				position = model.coreModel.isoMap.getCurrentMousePosition(mX,mY);
				soldier = model.company.getSoldier(simpleObject.identifier);
            	var bd:BitmapData = soldierDesigner.getSelectedNeutralBitmap(false,model.armyModule.getBitmapForSoldierCode(soldier.profile.@code));
            	soldier.soldierIso.bitmapData = bd;
            	soldier.selected = true;
            	
				for(var i:int = 0; i < model.company.soldiers.length;i++){
	    			var s:Soldier = (model.company.soldiers[i] as Soldier);
	    			if( s!=soldier && s.selected ) {
	    				s.selected = false;
	    				s.soldierIso.bitmapData = soldierDesigner.getNeutralBitmap(s.isCaptain,model.armyModule.getBitmapForSoldierCode(s.profile.@code));		    						    					
	    			}
	    		}								
            	model.coreModel.isoMap.doRetrace = true;   
            	model.coreModel.isoMap.invalidateProperties();            															
				dispatchEvent(new Event("selected"));
				this.systemManager.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler,true);
				this.systemManager.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler,true);
				
			} else {
				model.coreModel.autoScrollingIsOn = false;
			}
			event.updateAfterEvent();
		}
		public function mouseUpHandler(event:MouseEvent):void {
			this.systemManager.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler,true);
			model.coreModel.autoScrollingIsOn = false;			
			model.coreModel.isoMap.removeAllAPE(ar);
			ar = null;
			lastMouseX = -1;
			this.systemManager.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler,true);
		}
		public function mouseMoveHandler(event:MouseEvent):void {
			var mX:int = model.coreModel.isoMap.mouseX + decalageX;
			var mY:int = model.coreModel.isoMap.mouseY + decalageY;
			if( lastMouseX != -1 ) {
				var d:Number = CollisionManager.distance(mX,mY,lastMouseX,lastMouseY);
				if( d > 16 ) {
					var dd:Number = d/16;
					mX = lastMouseX + (mX - lastMouseX)/dd;
					mY = lastMouseY + (mY - lastMouseY)/dd;
				}
			} 
			lastMouseX = mX;
			lastMouseY = mY;
			var position:IsoMapMouseEvent = model.coreModel.isoMap.getCurrentMousePosition(mX,mY);
			if( position.isoTile ) {				
				if( ar == null || Math.abs(position.isoTile.x2d - isoTileCharacterCenter.x2d)>=2 
				||  Math.abs(position.isoTile.y2d - isoTileCharacterCenter.y2d)>=2 ) {
					isoTileCharacterCenter = position.isoTile;
					model.coreModel.isoMap.removeAllAPE(ar);
					ar = model.coreModel.isoMap.populateAroundAPE(isoTileCharacterCenter);
				}
								
				soldier.soldierIso.particle.px = position.point2d.x;
	            soldier.soldierIso.particle.py = position.point2d.y;
	            soldier.soldierIso.particle.fixed = false;
	            APEngine.step();
	            soldier.soldierIso.particle.fixed = true;
		        //APEngine.paint();	      
		        
		        if( ! soldier.soldierIso.particle.hasCollided ) {
		        	var lastX2d:int = soldier.soldierIso.particle.px;
	            	var lastY2d:int = soldier.soldierIso.particle.py;
	            	
	            	if( Math.abs(lastX2d - soldier.soldierIso.ox) < 47 &&  Math.abs(lastY2d - soldier.soldierIso.oy) < 47) {
	            			        	
            			model.coreModel.isoMap.place(soldier.soldierIso, lastX2d,lastY2d);
            			model.coreModel.isoMap.isotile = model.coreModel.isoMap.testIsoTile(lastX2d,lastY2d);
	            		model.coreModel.isoMap.doRetraceIsotile = true;
			    		model.coreModel.isoMap.invalidateProperties();
			    		event.updateAfterEvent();
			    		
	            	}
		        				    	
		        } 
		      
		        
			}          		    
		}
		public function attach():void {
			this.systemManager.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler,true);
			
		}
		public function detach():void {
			this.systemManager.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler,true);
			this.systemManager.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler,true);
			this.systemManager.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler,true);
			
			this._soldier = null;
		}
		
		public function get soldier ():Soldier {
			return _soldier;
		}
		public function set soldier (s:Soldier):void {
			_soldier = s;
		}

	}
}